<template>
  <div class="cartcontrol">
    <transition name="move">
      <div class="cart-decrease" v-show="foodcount > 0" @click="decreaseCart">
        <span class="icon-remove_circle_outline"></span>
      </div>
    </transition>
    <div class="cart-count" v-show="foodcount > 0">{{ foodcount }}</div>
    <div class="icon-add_circle" @click="addCart"></div>
  </div>
</template>

<script>
import Vue from "vue";
export default {
  name: "cartcontrol",
  props: ["food"],
  data: () => ({
    /* cart: [], */
  }),
  computed: {
    foodcount() {
      let state = this.$store.state;
      let num = 0;
      state.cart.forEach((item) => {
        if (this.food.name === item.name) num = item.count;
      });
      return num;
    },
    cart() {
      return this.$store.state.cart;
    },
  },
  methods: {
    addCart() {
      if (!this.food.count) {
        /* 给一个观测对象
           Vue.set( target, key, value )
           target：要更改的数据源(可以是对象或者数组)
           key：要更改的具体数据
           value ：重新赋的值                       */
        Vue.set(this.food, "count", 0);
      }
      // 将菜品添加到 购物车
      //this.$store.commit('addToCart',this.food);
      this.$store.dispatch("aAddToCart", this.food);
    },
    decreaseCart() {
      // 删除购物车的对应选项
      if (this.food.count >= 1) {
        // 数量自减
        this.$store.dispatch("adecreaseFromCart", this.food);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.cartcontrol {
  .cart-decrease {
    display: inline-block;
    opacity: 1;
    transition: translated(0, 0, 0);

    &.move-enter-active,
    &.move-leave-active {
      transition: all 0.4s linear;
    }

    &.move-enter,
    &.move-leave-active {
      opacity: 0;
      transform: translate3d(24px, 0, 0);
      .icon-remove_circle_outline {
        transform: rotate(180deg);
      }
    }
  }

  .cart-count {
    display: inline-block;
    width: 24px;
    text-align: center;
    vertical-align: top;
    font-size: $xs-size;
    color: $e-dgrey;
    line-height: 24px;
  }
  .icon-add_circle,
  .icon-remove_circle_outline {
    display: inline-block;
    font-size: 24px;
    line-height: 24px;
    color: $e-dblue;
  }
  .icon-remove_circle_outline {
    transition: all 0.4s linear;
    transform: rotate(0);
  }
}
</style>